/**
 * Created by Wing on 2017/5/25.
 */
var request = getRequest();
var _deckId = request["deckId"];
var _curPage;
$(function () {
    getNoteData(_deckId, 1);
    getCurrentDeckName();
});
var getNoteData = function (deckId, curPage) {
    var searchText = "";
    if($("#searchTextInput").val().trim().length > 0){
        searchText = $("#searchTextInput").val().trim();
    }
    if (deckId == undefined) {
        deckId = _deckId;
    }
    if (curPage == undefined) {
        if (_curPage != undefined) {
            curPage = _curPage;
        } else {
            curPage = 1;
            _curPage = 1;
        }
    } else {
        _curPage = curPage;
    }
    $.getJSON(
        "/memorypalace/knowledge/toaddknowledgetree.action?deckId=" + deckId + "&curPage=" + curPage + "&pageCount=9" + "&searchText="+searchText,
        function (notesInPage) {
            var noteList = notesInPage.data;
            var recordNum = notesInPage.recordNum;
            var totalPage = notesInPage.totalPage;

            pageControll(curPage, totalPage);

            $("#products").html("");
            $.each(noteList, function (i, note) {

                var h =
                    '<div class="item  col-xs-4 col-lg-4" >' +
                    '<div class="thumbnail" style="position: relative" value="' + note.noteId + '">' +
                    '<div class="panel panel-default" style="border: none;margin-bottom: 0px;height:200px;overflow-x:hidden;overflow-y: auto;">';
                var areaNames = JSON.parse(note.areaNames);
                var areaContents = JSON.parse(note.areaContents);
                $.each(areaNames, function (j, areaName) {
                    if (j == 0) {
                        h +=
                            '<div class="panel-heading" >' +
                            '   <h3 class="panel-title">' + areaContents[0] + '</h3>' +
                            '</div>';
                    } else {
                        h +=
                            '<div class="panel-body">' + areaContents[j] + '</div>';
                    }
                });
                h +=
                    '</div>' +
                    '<img class="deleteImg" src="http://localhost:8080/memorypalace//websrc/img/delete.png">' +
                    '<img class="editImg" src="http://localhost:8080/memorypalace//websrc/img/edit.png">' +
                    '</div>' +
                    '</div>';
                $("#products").append(h);

            });

            $(".deleteImg").hide();
            $(".editImg").hide();
            // 添加点击事件
            $(".thumbnail").mouseover(function (ev) {
                var div = $(ev).attr("delegateTarget");
                $(div).addClass("selected");
                $(".selected .deleteImg").show();
                $(".selected .editImg").show();
            })
            $(".thumbnail").mouseout(function (ev) {
                var div = $(ev).attr("delegateTarget");
                $(".selected .deleteImg").hide();
                $(".selected .editImg").hide();
                $(div).removeClass("selected");
            })
            $(".thumbnail").click(previewNote);
            $(".editImg").click(beforeeditNote);
            $(".deleteImg").click(deleteNote);
            $(".card").off();
            $(".card").click(preview);

        }
    );
}
var pageControll = function (curPage, totalPage) {
    $("#pageNav").html("");
    // 首页
    var h = '<li>' +
        '<a href="javascript:getNoteData(undefined,1)" aria-label="Previous">' +
        '<span aria-hidden="true">&laquo;</span>' +
        '</a>' +
        '</li>';

    if (totalPage <= 5) {
        // 如果是小于等于5,不需要缩略的情况
        for (var i = 1; i <= totalPage; i++) {
            if (i != curPage) {
                h += '<li><a href="javascript:getNoteData(undefined,' + i + ')">' + i + '</a></li>';
            } else {//class="active"
                h += '<li class="active"><a href="javascript:getTableDataByDeck(undefined,' + i + ',1)">' + i + '</a></li>';
            }
        }
    } else {
        var low = curPage - 2;
        var hight = curPage + 2;
        if (curPage <= 2) {
            low = 1;
            hight = 5;
        }
        if (curPage >= totalPage - 2) {
            hight = totalPage;
            low = totalPage - 4;
        }
        for (var i = low; i <= hight; i++) {
            var content = i;
            if (i == low) {
                content = "..." + i;
            }
            if (i == hight) {
                content = i + "...";
            }
            if (i != curPage) {
                h += '<li><a href="javascript:getNoteData(undefined,' + i + ')">' + content + '</a></li>';
            } else {//class="active"
                h += '<li class="active"><a href="javascript:getNoteData(undefined,' + i + ')">' + content + '</a></li>';
            }
        }
    }
    // 尾页
    h += '<li>' +
        '<a href="javascript:getNoteData(undefined,' + totalPage + ')"' +
        ' aria-label="Previous">' +
        '<span aria-hidden="true">&raquo;</span>' +
        '</a>' +
        '</li>';
    if(totalPage == 0){
        h = '';
    }
    $("#pageNav").html(h);
}

var previewNote = function () {
    var noteId;
    var selecteds = $(".thumbnail.selected");

    noteId = $(selecteds).attr("value");
    $.getJSON(
        "/memorypalace/note/getnotebynoteid.action",
        {noteId:noteId},
        function (note) {
            _noteForPreview = note;
            $("#notePreviewA span").click();// 窗口显示
            //配置内容
            previewIndex = 0;
            preview();
        }
    );
}
var _noteForPreview;
var previewIndex = 0;
var preview = function () {
    $(".card").html("");
    var indexForCardStyle = parseInt(previewIndex/2);
    if(indexForCardStyle >= _noteForPreview.noteType.cardStyleList.length){
        // 超出范围
        $("#notePreview .md-close span").click();
    }else {

        var currentCardStyle = _noteForPreview.noteType.cardStyleList[indexForCardStyle];
        var html;
        if (previewIndex % 2 == 0) {// 显示正面
            html = currentCardStyle.frontHTML;
        } else {
            html = currentCardStyle.backHTML;
            html = html.replace("{{FrontSide}}",currentCardStyle.frontHTML);
        }
        // 牌组名称
        html = html.replace("{{Deck}}",_deck.deckName);
        var areaContentsJSON = JSON.parse(_noteForPreview.areaContents);
        var areaNamesJSON = JSON.parse(_noteForPreview.areaNames);

        $.each(areaNamesJSON, function (i, areaName) { //正面
            // 替换区域
            var regRexit = new RegExp("\{\{"+areaName+"\}\}");
            html = html.replace(regRexit, areaContentsJSON[i]);
            // 替换条件区域
            var regCondition = new RegExp("\{\{\#"+areaName+"\}\}");
            var regEndCondition = new RegExp("\{\{\/"+areaName+"\}\}");
            var s = html.match(regCondition);
            if(html.match(regCondition) != undefined){
                if(areaContentsJSON[i].trim().length == 0) {
                    html = html.replace(regCondition, "<!--");
                    html = html.replace(regEndCondition, "-->");
                }else{
                    html = html.replace(regCondition, "");
                    html = html.replace(regEndCondition, "");
                }
            }
        });
        $(".card").html(html);

        $("#cardCss").html(currentCardStyle.css);
        previewIndex++;
    }

}
var _deck;
var getCurrentDeckName = function () {
    $.ajax({
        url:"/memorypalace/getdeckbydeckid.action",
        data:{deckId:_deckId},
        dataType:"json",
        success:function (deck) {
            $("#currentDeckName").html(deck.deckName);
            _deck = deck;
        },
        error:function (err) {
            console.log(err);
        }
    });
}